package com.m31skytech.dungeonstool.events;

import com.m31skytech.dungeonstool.blockentitys.TeleportControlBlockEntity;
import com.m31skytech.dungeonstool.blockentitys.TeleportPointBlockEntity;
import net.minecraft.core.BlockPos;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.LevelAccessor;
import net.minecraft.world.level.block.entity.BlockEntity;
import net.minecraftforge.event.level.BlockEvent;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.common.Mod;

//注释使forge注册该类下的处理器
@Mod.EventBusSubscriber(bus = Mod.EventBusSubscriber.Bus.FORGE)
public class BlockBreakEventHandler {

    @SubscribeEvent
    public static void onBlockBreak(BlockEvent.BreakEvent event) {
        // 获取被破坏的方块实体
        BlockEntity blockEntity =
                event.getLevel().getBlockEntity(event.getPos());
        teleportBlockHandler(event,blockEntity);
    }


    /**传送方块相关处理
     *
     * @param event
     * @param blockEntity
     */
    private static void teleportBlockHandler(BlockEvent.BreakEvent event,BlockEntity blockEntity){
        if (null!= blockEntity){
            if (blockEntity instanceof TeleportControlBlockEntity controlBlockEntity) {
                // 处理传送控制方块的破坏事件
                BlockPos bindPos = controlBlockEntity.getBindPos();
                if (bindPos != null) {
                    // 删除绑定点的绑定信息
                    removeBindInfo(event.getLevel(), bindPos);
                }
            } else if (blockEntity instanceof TeleportPointBlockEntity pointBlockEntity) {
                // 处理传送点的破坏事件
                BlockPos controlBlockPos = pointBlockEntity.getBindPos(); // 假设你有这个方法
                if (controlBlockPos != null) {
                    // 删除传送控制方块的绑定信息
                    removeBindInfo(event.getLevel(), controlBlockPos);
                }
            }

        }
    }

    private static void removeBindInfo(LevelAccessor world, BlockPos pos) {
        BlockEntity blockEntity = world.getBlockEntity(pos);
        if (blockEntity instanceof TeleportControlBlockEntity controlBlockEntity) {
            controlBlockEntity.setBindPos(null,null);
        } else if (blockEntity instanceof TeleportPointBlockEntity pointBlockEntity) {
            pointBlockEntity.setBindPos(null,null);
        }
    }

}
